<?php


namespace app\common\job;

use app\common\model\order\OrderAction;
use app\common\model\order\OrderModel;
use app\common\model\order\OrderRefundModel;
use think\queue\Job;

/**
 * 售后订单异步操作
 */
class OrderRefundAutoOper
{

    /**
     * 后台审核通过后,用户超时未发货,关闭订单
     */
    public function NoSendCloseOrder(Job $job, $data)
    {
        try {
            // 重新查询订单
            \think\Log::write('queue-' . get_class() . '-NoSendCloseOrder' . '：执行成功');
            $orderRefund = OrderRefundModel::get($data['order_refund_id']);

            if ($orderRefund && $orderRefund->status == 1 && $orderRefund->is_close == 0) {
                \think\Db::transaction(function () use ($orderRefund, $data) {
                    // 关闭订单
                    $orderRefund->is_close = 1;
                    $orderRefund->close_time = time();
                    $orderRefund->save();

                    $update = [
                        'is_sales' => 0,
                        'refund_no' => null,
                        'refund_status' => null,
                    ];
                    \app\common\model\order\OrderGoodsModel::where(['id'=>$orderRefund->order_goods_id])->update($update);
                    $OrderGoods = \app\common\model\order\OrderGoodsModel::where(['order_id'=>$orderRefund->order_id])->column('id,is_sales');
                    $is_sales = 0;
                    foreach ($OrderGoods as $key => $val){
                        if($val['is_sales'] > 0){
                            $is_sales += 1;
                        }
                    }
                    if($is_sales == 0){
                        \app\common\model\order\OrderModel::where(['id'=>$orderRefund->order_id])->update(['is_sales'=>0]);
                    }

                    $order = OrderModel::get($orderRefund->order_id);
                    $order->aftersale_status = 4;
                    OrderAction::operAdd($order, null, null, 'system', '系统自动失效订单');
                });
            }
            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-NoSendCloseOrder' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }
}